package com.snack.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.snack.shop.common.BusinessException;
import com.snack.shop.dto.FeedbackSubmitRequest;
import com.snack.shop.dto.FeedbackAppendRequest;
import com.snack.shop.dto.FeedbackReplyRequest;
import com.snack.shop.entity.Feedback;
import com.snack.shop.entity.FeedbackReply;
import com.snack.shop.mapper.FeedbackMapper;
import com.snack.shop.mapper.FeedbackReplyMapper;
import com.snack.shop.service.FeedbackService;
import com.snack.shop.service.FileManageService;
import com.snack.shop.service.MessageService;
import com.snack.shop.service.MerchantMessageService;
import com.snack.shop.mapper.UserMapper;
import com.snack.shop.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 意见反馈服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FeedbackServiceImpl implements FeedbackService {

    private final FeedbackMapper feedbackMapper;
    private final FeedbackReplyMapper feedbackReplyMapper;
    private final ObjectMapper objectMapper;
    private final FileManageService fileManageService;
    private final MessageService messageService;
    private final MerchantMessageService merchantMessageService;
    private final UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Feedback submitFeedback(Long userId, FeedbackSubmitRequest request) {
        if (userId == null) {
            throw new BusinessException("未登录");
        }

        // 参数校验
        if (request.getContent() == null || request.getContent().trim().isEmpty()) {
            throw new BusinessException("反馈内容不能为空");
        }

        String content = request.getContent().trim();
        if (content.length() < 5) {
            throw new BusinessException("反馈内容最少5字");
        }
        if (content.length() > 1000) {
            throw new BusinessException("反馈内容最多1000字");
        }

        if (request.getType() == null || request.getType() < 1 || request.getType() > 6) {
            throw new BusinessException("反馈类型不合法");
        }

        // 检查图片数量
        if (request.getImages() != null && request.getImages().size() > 9) {
            throw new BusinessException("图片最多9张");
        }

        // 创建反馈记录
        Feedback feedback = new Feedback();
        feedback.setFeedbackNo(generateFeedbackNo());
        feedback.setUserId(userId);
        feedback.setType(request.getType());
        feedback.setContent(content);
        feedback.setContact(request.getContact());
        feedback.setOrderId(request.getOrderId());
        feedback.setOrderNo(request.getOrderNo());
        feedback.setStatus(0); // 待处理
        feedback.setReplyCount(0);
        feedback.setIsRead(0);

        // 转换图片列表为JSON
        if (request.getImages() != null && !request.getImages().isEmpty()) {
            try {
                feedback.setImages(objectMapper.writeValueAsString(request.getImages()));
            } catch (Exception e) {
                log.error("转换图片列表失败", e);
                throw new BusinessException("图片处理失败");
            }
        }

        feedbackMapper.insert(feedback);
        log.info("反馈提交成功，feedbackId: {}, userId: {}", feedback.getId(), userId);

        // 写入消息：反馈提交成功
        try {
            messageService.create(userId, 2, "反馈提交成功", "我们已收到您的反馈，编号" + feedback.getFeedbackNo(), "feedback", feedback.getId());
        } catch (Exception e) {
            log.warn("创建反馈消息失败, feedbackId={}", feedback.getId(), e);
        }

        // 为商家创建消息：新反馈提醒
        try {
            Long merchantId = getMerchantId();
            if (merchantId != null) {
                merchantMessageService.create(merchantId, 4, "新反馈提醒", "收到用户反馈，编号" + feedback.getFeedbackNo(), "feedback", feedback.getId());
            }
        } catch (Exception e) {
            log.warn("创建商家消息失败, feedbackId={}", feedback.getId(), e);
        }

        // 确认上传的图片为正式文件
        try {
            if (request.getImages() != null && !request.getImages().isEmpty()) {
                fileManageService.confirmFiles(request.getImages(), "feedback", feedback.getId());
            }
        } catch (Exception e) {
            log.warn("确认反馈图片为正式文件失败, feedbackId={}", feedback.getId(), e);
        }

        return feedback;
    }

    @Override
    public Page<Feedback> getUserFeedbackPage(Long userId, Integer status, Integer pageNum, Integer pageSize) {
        if (userId == null) {
            throw new BusinessException("未登录");
        }

        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        // 统一去除“处理中”(1)状态：若传1按0处理
        if (status != null && status == 1) {
            status = 0;
        }

        LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<Feedback>()
                .eq(Feedback::getUserId, userId)
                .eq(status != null, Feedback::getStatus, status)
                .orderByDesc(Feedback::getCreateTime);

        return feedbackMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public Feedback getFeedbackDetail(Long feedbackId, Long userId) {
        if (feedbackId == null) {
            throw new BusinessException("反馈ID不能为空");
        }

        Feedback feedback = feedbackMapper.selectById(feedbackId);
        if (feedback == null) {
            throw new BusinessException("反馈不存在");
        }

        // 验证权限（用户只能查看自己的反馈）
        if (userId != null && !feedback.getUserId().equals(userId)) {
            throw new BusinessException("无权限查看此反馈");
        }

        return feedback;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appendFeedback(Long userId, Long feedbackId, FeedbackAppendRequest request) {
        if (userId == null) {
            throw new BusinessException("未登录");
        }

        if (feedbackId == null) {
            throw new BusinessException("反馈ID不能为空");
        }

        Feedback feedback = feedbackMapper.selectById(feedbackId);
        if (feedback == null) {
            throw new BusinessException("反馈不存在");
        }

        // 验证权限
        if (!feedback.getUserId().equals(userId)) {
            throw new BusinessException("无权限追加此反馈");
        }

        // 检查反馈状态
        if (feedback.getStatus() == 3) {
            throw new BusinessException("已关闭的反馈不能追加");
        }

        // 参数校验
        if (request.getContent() == null || request.getContent().trim().isEmpty()) {
            throw new BusinessException("追加内容不能为空");
        }

        String content = request.getContent().trim();
        if (content.length() > 200) {
            throw new BusinessException("追加内容最多200字");
        }

        // 检查图片数量
        if (request.getImages() != null && request.getImages().size() > 3) {
            throw new BusinessException("追加图片最多3张");
        }

        // 创建回复记录（用户追加）
        FeedbackReply reply = new FeedbackReply();
        reply.setFeedbackId(feedbackId);
        reply.setReplyType(2); // 用户追加
        reply.setUserId(userId);
        reply.setContent(content);

        if (request.getImages() != null && !request.getImages().isEmpty()) {
            try {
                reply.setImages(objectMapper.writeValueAsString(request.getImages()));
            } catch (Exception e) {
                log.error("转换图片列表失败", e);
                throw new BusinessException("图片处理失败");
            }
        }

        feedbackReplyMapper.insert(reply);

        // 确认平台回复中的图片
        try {
            if (request.getImages() != null && !request.getImages().isEmpty()) {
                fileManageService.confirmFiles(request.getImages(), "feedback", feedbackId);
            }
        } catch (Exception e) {
            log.warn("确认平台回复图片失败, feedbackId={}", feedbackId, e);
        }

        // 更新反馈的回复次数和未读状态
        feedback.setReplyCount(feedback.getReplyCount() + 1);
        feedback.setIsRead(0); // 重新标记为未读
        feedbackMapper.updateById(feedback);

        // 写入消息：用户追加成功（可选）
        try {
            messageService.create(userId, 2, "反馈已追加", "您的反馈已追加成功，编号" + feedback.getFeedbackNo(), "feedback", feedbackId);
        } catch (Exception e) {
            log.warn("创建追加反馈消息失败, feedbackId={}", feedbackId, e);
        }

        // 确认追加反馈中的图片
        try {
            if (request.getImages() != null && !request.getImages().isEmpty()) {
                fileManageService.confirmFiles(request.getImages(), "feedback", feedbackId);
            }
        } catch (Exception e) {
            log.warn("确认追加反馈图片失败, feedbackId={}", feedbackId, e);
        }

        log.info("追加反馈成功，feedbackId: {}, userId: {}", feedbackId, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void markAsRead(Long feedbackId, Long userId) {
        if (feedbackId == null) {
            throw new BusinessException("反馈ID不能为空");
        }

        Feedback feedback = feedbackMapper.selectById(feedbackId);
        if (feedback == null) {
            throw new BusinessException("反馈不存在");
        }

        // 验证权限
        if (userId != null && !feedback.getUserId().equals(userId)) {
            throw new BusinessException("无权限操作此反馈");
        }

        feedback.setIsRead(1);
        feedbackMapper.updateById(feedback);
    }

    @Override
    public Page<Feedback> getAdminFeedbackPage(Integer type, Integer status, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        // 统一去除“处理中”(1)状态：若传1按0处理
        if (status != null && status == 1) {
            status = 0;
        }

        LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<Feedback>()
                .eq(type != null, Feedback::getType, type)
                .eq(status != null, Feedback::getStatus, status)
                .orderByDesc(Feedback::getCreateTime);

        return feedbackMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFeedbackStatus(Long feedbackId, Integer status) {
        if (feedbackId == null) {
            throw new BusinessException("反馈ID不能为空");
        }

        if (status == null) {
            throw new BusinessException("反馈状态不合法");
        }
        // 兼容：不再支持1-处理中；若传1按0-待处理处理
        if (status == 1) {
            status = 0;
        }
        if (!(status == 0 || status == 2 || status == 3)) {
            throw new BusinessException("反馈状态不合法");
        }

        Feedback feedback = feedbackMapper.selectById(feedbackId);
        if (feedback == null) {
            throw new BusinessException("反馈不存在");
        }

        feedback.setStatus(status);
        if (status == 2 || status == 3) {
            // 已处理或已关闭时记录处理时间
            feedback.setHandleTime(LocalDateTime.now());
        }
        feedbackMapper.updateById(feedback);

        log.info("反馈状态更新成功，feedbackId: {}, status: {}", feedbackId, status);

        // 写入消息：反馈状态更新
        try {
            String statusName = (status == 2 ? "已处理" : status == 3 ? "已关闭" : "待处理");
            messageService.create(feedback.getUserId(), 2, "反馈状态更新", "您的反馈已标记为" + statusName, "feedback", feedbackId);
        } catch (Exception e) {
            log.warn("创建反馈状态更新消息失败, feedbackId={}", feedbackId, e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void replyFeedback(Long feedbackId, Long handlerId, FeedbackReplyRequest request) {
        if (feedbackId == null) {
            throw new BusinessException("反馈ID不能为空");
        }

        if (request.getContent() == null || request.getContent().trim().isEmpty()) {
            throw new BusinessException("回复内容不能为空");
        }

        String content = request.getContent().trim();
        if (content.length() > 500) {
            throw new BusinessException("回复内容最多500字");
        }

        Feedback feedback = feedbackMapper.selectById(feedbackId);
        if (feedback == null) {
            throw new BusinessException("反馈不存在");
        }

        // 创建回复记录（平台回复）
        FeedbackReply reply = new FeedbackReply();
        reply.setFeedbackId(feedbackId);
        reply.setReplyType(1); // 平台回复
        reply.setUserId(handlerId);
        reply.setContent(content);

        if (request.getImages() != null && !request.getImages().isEmpty()) {
            try {
                reply.setImages(objectMapper.writeValueAsString(request.getImages()));
            } catch (Exception e) {
                log.error("转换图片列表失败", e);
                throw new BusinessException("图片处理失败");
            }
        }

        feedbackReplyMapper.insert(reply);

        // 更新反馈信息（不再使用处理中状态）
        feedback.setReplyCount(feedback.getReplyCount() + 1);
        feedback.setHandlerId(handlerId);
        feedback.setIsRead(0); // 标记为用户未读
        feedbackMapper.updateById(feedback);

        // 写入消息：收到平台回复
        try {
            String snippet = content.length() > 30 ? content.substring(0, 30) + "..." : content;
            messageService.create(feedback.getUserId(), 2, "收到平台回复", snippet, "feedback", feedbackId);
        } catch (Exception e) {
            log.warn("创建平台回复消息失败, feedbackId={}", feedbackId, e);
        }

        log.info("反馈回复成功，feedbackId: {}, handlerId: {}", feedbackId, handlerId);
    }

    @Override
    public List<FeedbackReply> getFeedbackReplies(Long feedbackId) {
        if (feedbackId == null) {
            throw new BusinessException("反馈ID不能为空");
        }

        return feedbackReplyMapper.selectList(
                new LambdaQueryWrapper<FeedbackReply>()
                        .eq(FeedbackReply::getFeedbackId, feedbackId)
                        .orderByAsc(FeedbackReply::getCreateTime)
        );
    }

    /**
     * 生成反馈编号
     */
    private String generateFeedbackNo() {
        return "FB" + System.currentTimeMillis() + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
    }

    /**
     * 获取商家ID（单商户模式：查询 user_type=3 的用户）
     */
    private Long getMerchantId() {
        try {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUserType, 3) // user_type=3 为商家
                   .last("limit 1");
            User merchant = userMapper.selectOne(wrapper);
            return merchant != null ? merchant.getId() : null;
        } catch (Exception e) {
            log.error("获取商家ID失败", e);
            return null;
        }
    }
}
